<?php
namespace app\admin\controller;

class Login extends Base
{
    public function login()
    {
        if ($this->check_login() !== false) {
            $this->redirect('/admin/index/index');
        }
        if ($this->post) {
            if (isset($this->post['captcha'])) {
                if (!captcha_check($this->post['captcha'])) {
                    $this->returnAPI('验证码有误');
                }
            }
            $admin = model('admin')->get(['username' => $this->post['username']]);
            if (is_null($admin)) {
                $this->returnAPI('账号不存在');
            }
            if ($admin->password !== $this->post['password']) {
                $this->returnAPI('密码不正确');
            }
            if ($admin->disabled) {
                $this->returnAPI('账号被禁用');
            }
            if ($admin->role) {
                $role = model('role')->get($admin->role);
                if (is_null($role) || $role->disabled) {
                    $this->returnAPI('账号无权限');
                }
            }
            session('admin_id', $admin->id);
            if (isset($this->post['remember']) && $this->post['remember']) {
                cookie('admin_login', simple_encrypt($admin->id . '@@@' . $admin->password), 30 * 86400);
            }
            $this->returnAPI('登录成功', 0);
        }
        return $this->fetch();
    }

    public function logout()
    {
        session('admin_id', null);
        cookie('admin_login', null);
        $this->returnAPI('退出登录成功', 0);
    }
}
